package com.yinbo.database;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanListHandler;

import com.yinbo.database.DbConnectionManager;
import com.yinbo.model.Page;

/**
 * Handle common JDBC operation with generic.
 * 
 * @author Y.N
 */
public class JdbcTemplate {

	private JdbcTemplate() {
	}

	/**
	 * 查询结果中的整型值，传入的 SQL 应是一个统计语句
	 * 
	 * @param sql
	 * @return
	 * @throws SQLException
	 */
	public static int queryForInt(String sql) throws SQLException {
		int intValue = 0;
		Connection connection = null;
		Statement stmt = null;
		ResultSet rs = null;
		try {
			connection = DbConnectionManager.getConnection();
			stmt = connection.createStatement();
			rs = stmt.executeQuery(sql);
			if (rs.next()) {
				intValue = rs.getInt(1);
			}

		} catch (SQLException e1) {
			e1.printStackTrace();
		} finally {
			DbConnectionManager.closeConnection(rs, stmt, connection);
		}
		return intValue;
	}

	/**
	 * 使用mysql 的分页语句进行分页查询
	 * 
	 * @param sql
	 * @param first
	 * @param max
	 * @param type
	 * @return
	 * @throws SQLException
	 */
	public static List queryListByLimit(String sql, int first, int max,
			Class type) throws SQLException {
		List rs = new ArrayList();
		Connection connection = null;
		try {
			connection = DbConnectionManager.getConnection();
			StringBuilder sb = new StringBuilder(sql);
			sb.append(" limit ").append(first).append(',').append(max);
			QueryRunner qRunner = new QueryRunner();
			rs = (List) qRunner.query(connection, sb.toString(),new BeanListHandler(type));

		} catch (SQLException e1) {
			e1.printStackTrace();
		} finally {
			DbConnectionManager.closeConnection(connection);
		}
		return rs;
	}

	/**
	 * 根据传入的 PAGE 对象 ，使用mysql 的分页语句进行分页查询
	 * 
	 * @param sql
	 * @param first
	 * @param max
	 * @param type
	 * @return
	 * @throws SQLException
	 */
	public static List queryByPage(String selectCountSql, String selectSql,Page page, Class type) throws SQLException {
		int count = JdbcTemplate.queryForInt(selectCountSql);
		if (count == 0) {
			page.setTotalCount(0);
			return Collections.emptyList();
		}
		page.setTotalCount(count);
		return queryListByLimit(selectSql, page.getFirstResult(), page.getPageSize(), type);
	}

	/**
	 * 将传入的SQL 执行，返回 结果集，以CLASS 的方式封装
	 * 
	 * @param sql
	 * @param first
	 * @param max
	 * @param type
	 * @return
	 * @throws SQLException
	 */
	public static List queryForList(String sql, Class type) throws SQLException {
		Connection connection = null;
		List query = new ArrayList();
		try {
			connection = DbConnectionManager.getConnection();
			StringBuilder sb = new StringBuilder(sql);
			QueryRunner qRunner = new QueryRunner();
			query = (List) qRunner.query(connection, sb.toString(),new BeanListHandler(type));
		} catch (SQLException e1) {
			e1.printStackTrace();
		} finally {
			DbConnectionManager.closeConnection(connection);
		}
		return query;
	}

	/**
	 * 执行更新
	 * 
	 * @param sql
	 * @param params
	 * @return
	 * @throws Exception
	 */
	public static int executeUpdate(String sql, Object[] params)
			throws Exception {
		Connection connection = null;
		PreparedStatement ps = null;
		int executeUpdate = -1;
		try {
			connection = DbConnectionManager.getConnection();
		} catch (SQLException e1) {
			e1.printStackTrace();
		}
		try {
			ps = connection.prepareStatement(sql);
			bindParameters(ps, params);
			executeUpdate = ps.executeUpdate();
		} catch (SQLException e) {
			throw new Exception(e);
		} finally {
			DbConnectionManager.closeConnection(ps, connection);
		}
		return executeUpdate;
	}
	
	/**
	 * 修改单个列值
	 * @param sql
	 * @return
	 * @throws Exception
	 */
	public static int executeUpdateOne(String sql)throws Exception {
		Connection connection = null;
		Statement stmt = null;
		
		int executeUpdate = -1;
		try {
			connection = DbConnectionManager.getConnection();
		} catch (SQLException e1) {
			e1.printStackTrace();
		}
		try {
			stmt = connection.createStatement();
			executeUpdate = stmt.executeUpdate(sql);
		} catch (SQLException e) {
			throw new Exception(e);
		} finally {
			DbConnectionManager.closeConnection(stmt, connection);
		}
		return executeUpdate;
	}

	/**
	 * 将PreparedStatement 的参数放入 PreparedStatement 中
	 * 
	 * @param ps
	 * @param params
	 * @throws SQLException
	 */
	private static void bindParameters(PreparedStatement ps, Object[] params)
			throws SQLException {
		if (params != null) {
			for (int i = 0; i < params.length; i++) {
				ps.setObject(i + 1, params[i]);
			}
		}
	}
	
	
}
